package Algorithm;

//遍历法单链表反转
public class ReversalNode {
    public static void main(String[] args) {
        ReversalNode reversalNode = new ReversalNode();
        Node head = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        head.Next = node1;
        node1.Next = node2;
        node2.Next = node3;
        node3.Next = null;
        Node h = head;
        while (h != null) {
            System.out.print(h.Data);
            h = h.Next;
        }
        System.out.println();
        Node newH = reversalNode.reverse2(head);
        while (newH != null) {
            System.out.println(newH.Data);
            newH = newH.Next;
        }
    }

    /**
     * 遍历，将当前节点的下一个节点缓存后更改当前节点指针
     */
    public Node reverse(Node head) {
        Node pre = null;
        Node next = null;

        while (head != null) {
            next = head.Next;
            head.Next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
    public static Node reverse2(Node head) {
        // head看作是前一结点，head.getNext()是当前结点，reHead是反转后新链表的头结点
        if (head == null || head.Next == null) {
            return head;// 若为空链或者当前结点在尾结点，则直接还回
        }
        Node reHead = reverse2(head.Next);// 先反转后续节点head.getNext()
        head.Next=head;// 将当前结点的指针域指向前一结点
        head=null;// 前一结点的指针域令为null;
        return reHead;// 反转后新链表的头结点
    }

}

class Node {
    public int Data;// 数据域
    public Node Next;// 指针域

    public Node(int Data) {
        // super();
        this.Data = Data;
    }

    public int getData() {
        return Data;
    }

    public void setData(int Data) {
        this.Data = Data;
    }
}
